$(function() {
    var cols=6;
	var rows_delete=0;
	var mode="add";
	var m_id=0;
    var url='controls/student_assign_model.php';
    var cboObj;
	var objSelectTable=[];
	
	initialData();
	
	 function initialData(){
		$.get(url,{"m":"age_level"} , function(data){
			$("#age_level").html(data);
		});
		$.get(url, {"m":"class"},function(data){
			cboObj=eval('('+data+')');	
			if (cboObj != null){
				$.each(cboObj, function(index, text) {
					
					$("#cboClassSearch").append(
							$('<option></option>').val(text).html(index)
					);
					 
				});
			}
			LoadData(1);
		});
		 

	}
		 
	 function LoadData(cid){
		BlockUI();
        $( "#resultData tbody tr" ).remove();
 
		$.post(url,{'m':'getRoom_amt','cid':cid},function(data){
			$("#roomInfo").html(data);
		});
		
 
        $('#resultData').dataTable( {
			"bProcessing": true,
			"bFilter": false,
			 "bPaginate": true,
			"bLengthChange": false,
			"sAjaxSource": url,
			"oLanguage": {
				"sEmptyTable":     "ไม่พบข้อมูล"
			},
			"bDestroy": true,
			"sServerMethod": "POST",
			"fnServerParams": function ( aoData ) {
					aoData.push( { "name": "m", "value": "load" },
								{"name":"cl_id","value":cid}
							);
				},
			"aoColumnDefs":[
				{  "bVisible": false , "aTargets": [ 1 ] },	
				{  "bVisible": false , "aTargets": [ 2 ] },	
				{  "bVisible": false , "aTargets": [ 3 ] },	
				{   "bSortable": true, "aTargets": [ 4 ] ,"sClass":"left"},	
				{   "bSortable": true, "aTargets": [ 5 ] ,"sClass":"center" },	//Create date
				{   "bSortable": true, "aTargets": [ 6 ] ,"sClass":"center" },	//Register date
				{   "bSortable": true, "aTargets": [ 7 ] ,"sClass":"center" },	
				{   "bSortable": true, "aTargets": [ 8 ] ,"sClass":"center" },	
				{   "bSortable": true, "aTargets": [ 9 ], "sClass":"center",
					"mRender": function ( data, type, full ) {
						var tmp="";
						if (full[2]=='1')
							tmp="<font style='color:green !important;'>"+ data +"</font>";
						else
							tmp="<font style='color:red !important;'>ยกเลิก</font>";
						return tmp;}
				},
				{  "bVisible": false , "aTargets": [ 10 ] },	
				{ "aTargets": [ 11 ],
					"sClass":"center",
					"mData": null,
					"mRender": function ( data, type, full ) {
							var cbo_html="<div class='controls' style='margin-left:0px;'><select class='span2 m-wrap cbo_class' name='cbclass' style='width:130px !important;'> ";
							cbo_html += "<option value='0' >ไม่ถึงเกณฑ์</option>";
							$.each(cboObj, function(index, text) {
								var select = "";
								
								if (full[3] == text)
									select = "selected";
									
								cbo_html += "<option value='"+text+"' "+select+" >"+index+"</option>";
							});
							cbo_html += "</select></div>";
							return cbo_html;
					}
				},
				{"aTargets": [ 12 ],
					"sClass":"center",
					"mData": null,
					"mRender": function ( data, type, full ) {
						var cbo_html="<div class='controls' style='margin-left:0px;'><select class='span2 m-wrap cbo_room' name='cbroom' style='width:60px !important;'> ";
						var obj= full[10];
						$.each(obj, function(index, text) {
								cbo_html += "<option value='"+text+"' >"+index+"</option>";
							});
							cbo_html += "</select></div>";
							return cbo_html;
					}
				},
				{"aTargets": [ 13 ],
					"sClass":"center",
					"mData": null,
					"mRender": function ( data, type, full ) {
						return "<a href='student_detail.php'><button   style='height:30px;' class='btn btn-inverse btnView'><i class='icon-folder-open'></i></button></a>";
					}
				}
			],"fnDrawCallback": function ( oSettings ) {
				 var that = this;
				/* Need to redo the counters if filtered or sorted */
                 var iTotalRecords = oSettings.fnRecordsTotal();
 
					if (iTotalRecords > 0){ 	
						if ( oSettings.bSorted || oSettings.bFiltered )
						{
							for ( var i=0, iLen=oSettings.aiDisplay.length ; i<iLen ; i++ )
							{
								$('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr ).html( i+1 );
							}
						}
					}
					setTimeout(function(){$.unblockUI();},2500);
				} 
		 } );
		 
      }
	  
	 $(".btnView").live('click',function(){
		var rows = $('#resultData').dataTable().fnGetPosition($(this).closest("tr").get(0));
		var data =$('#resultData').dataTable().fnGetData(rows);
		m_id = data[1];	
		
		var input = $("<input>")
               .attr("type", "hidden")
               .attr("name", "my").val(m_id);
		var input2=$("<input>")
               .attr("type", "hidden")
               .attr("name", "my_t").val("n");
			   
		$("#myForm").append($(input));
		$("#myForm").append($(input2));
		
		$("#myForm").submit();
	 });
	 
	 $(".cbo_class").live('change',function(){
	     var rowSelect=$(this).parent().parent().parent();
		 
		var cbroom = rowSelect.find("select[name=cbroom]");  
		cbroom.find('option').remove();	
		
		var cid= $(this).val();
		if (cid==0){
			cbroom.append($('<option></option>').val(0).html('--'));
		}else{
			$.post(url,{'m':'room','cid':cid},function(data){
				var obj=eval('('+data+')');	
				if (obj != null){
					$.each(obj, function(index, text) {
						cbroom.append(
								$('<option></option>').val(text).html(index)
						);
						 
					});
				}
			});
		}
	 });
	$("#btnCancel").click(function(){
		$('#table_detail').dataTable().fnClearTable();
		objSelectTable=[]
	});
	$("#btnSearch").click(function(){
		var _class_level = $("#cboClassSearch").val();
		LoadData(_class_level);
	});
  
	$("#btnSave").live('click',function(){
		  var main_table= $('#resultData').dataTable();
		  var detail_table=$('#table_detail').dataTable({ 
			"bFilter": false,
			"bDestroy": true,
			"bPaginate": false,
			"bLengthChange": false
			,"fnDrawCallback": function ( oSettings ) {
				 var that = this;
				/* Need to redo the counters if filtered or sorted */
                 var iTotalRecords = oSettings.fnRecordsTotal();
 
					if (iTotalRecords > 0){ 	
						if ( oSettings.bSorted || oSettings.bFiltered )
						{
							for ( var i=0, iLen=oSettings.aiDisplay.length ; i<iLen ; i++ )
							{
								$('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr ).html( i+1 );
							}
						}
					}
					 
				} 
		  });
		  
	   main_table.$('tbody tr').each(function() {
				
				var userData = main_table.fnGetData(this);
				var cbroom = $(this).find("select[name=cbroom]");  
				var cboclass= $(this).find("select[name=cbclass] option:selected").text(); 
				var cboclass_id= $(this).find("select[name=cbclass] option:selected").val(); 
				
				if (cboclass_id!=0){
					objSelectTable.push({'sid':userData[1],'cid':cboclass_id,'r':cbroom.val()});
					detail_table.fnAddData( [
						0,
						userData[1],
						cboclass_id,
						userData[4],
						userData[7],
						cboclass,
						cbroom.val()
					]);
					detail_table.fnSetColumnVis( 1, false );
					detail_table.fnSetColumnVis( 2, false );
			 
					 
				}
			});
		});		
	 
	$("#btnConfirm").click(function(){
		 if (objSelectTable.length>0){
			 
			 $.ajax({
					type: 'POST',
					cache: false,
					url: url,
					data: {'m':'add','list':objSelectTable},
					success: function(data){
						 
						LoadData($("#cboClassSearch").val());
						 $('#table_detail').dataTable().fnClearTable();
						 $("#popup").modal('hide');
						 
					}
			});
			 
		 }
	});
	$("#btnPrintDraft").click(function(){
	  $("#resultData").printThis();
		return false;
           
	});	
  
    
});


